/*
 * Copyright (c) 1994-2017, Joyoung Stock CO.LTD.
 * The FWJR Project.
 * All Rights Reserved.
 */

package com.rest.util;

import java.security.MessageDigest;

/**
 * Md5加密算法 说明：包含直接md5加密，salt值加密，二次加密。
 */
public class MD5Coder {

    /**
     * 带签名的MD5加密
     */
    public String encrypt2Str(byte[] value) {
        try {
            byte[] ex = encrypt(value);
            return bytes2HexString(ex).toUpperCase();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * byte数组转String
     */
    public String bytes2HexString(byte[] bytes) {
        final String HEX = "0123456789abcdef";
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        for (byte b : bytes) {
            // 取出这个字节的高4位，然后与0x0f与运算，得到一个0-15之间的数据，通过HEX.charAt(0-15)即为16进制数
            sb.append(HEX.charAt((b >> 4) & 0x0f));
            // 取出这个字节的低位，与0x0f与运算，得到一个0-15之间的数据，通过HEX.charAt(0-15)即为16进制数
            sb.append(HEX.charAt(b & 0x0f));
        }

        return sb.toString();
    }

    /**
     * MD5加密：直接加密
     */
    public byte[] encrypt(byte[] data) throws Exception {
        return encrypt(data, null, false);
    }

    /**
     * MD5加密：定位直接加密
     */
    public byte[] encrypt(byte[] data, int offset, int length) throws Exception {
        return encrypt(data, null, false, offset, length);
    }

    /**
     * MD5加密：是否做偏移加密
     */
    public byte[] encrypt(byte[] data, boolean isTwice) throws Exception {
        return encrypt(data, null, isTwice);
    }

    /**
     * MD5加密：salt加密
     */
    public byte[] encrypt(byte[] data, byte[] salt) throws Exception {
        return encrypt(data, salt, false);
    }

    /**
     * MD5加密：是否做偏移salt加密
     */
    public byte[] encrypt(byte[] data, byte[] salt, boolean isTwice) throws Exception {
        return encrypt(data, salt, isTwice, 0, data.length);
    }

    /**
     * md5加密
     */
    public byte[] encrypt(byte[] data, byte[] salt, boolean isTwice, int offset, int length) throws Exception {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update(data, offset, length);
        if ((salt != null) && (salt.length != 0)) {
            md5.update(salt);
        }
        byte[] md5Bytes = md5.digest();
        if (isTwice) {
            md5.update(md5Bytes, 8, 8);
            byte[] md52 = md5.digest();
            System.arraycopy(md52, 8, md5Bytes, 8, 8);
        }
        return md5Bytes;
    }
}
